<template>
  <div id="app">
    <div class="header">
      <button class="menu-toggle" @click="toggleSidebar">☰</button>
      <h1>Wonfu Doc - 接口文档中心</h1>
    </div>
    <div class="main-content">
      <Sidebar
        :api-data="apiData"
        :expanded-modules="expandedModules"
        :sidebar-hidden="sidebarHidden"
        :current-api-id="currentApi?.id || ''"
        @toggle-module="toggleModule"
        @show-api-detail="(api: SimpleApiInfo) => showApiDetail(api)"
      />
      <div class="content">
        <div class="api-content">
          <!-- 加载状态 -->
          <div class="loading" v-if="loading">
            <p>正在加载接口文档...</p>
          </div>
          
          <!-- 错误状态 -->
          <div class="empty-state" v-else-if="error">
            <h3>数据加载失败</h3>
            <p>{{ error }}</p>
          </div>
          
          <!-- 默认内容 -->
          <div v-else-if="!currentApi">
            <div class="stats-info">
              <div class="stat-item">
                <div class="stat-number">{{ totalCount }}</div>
                <div class="stat-label">总接口数</div>
              </div>
            </div>
            <div class="empty-state">
              <h3>欢迎使用 Wonfu Doc</h3>
              <p>请从左侧菜单选择一个接口查看详情</p>
            </div>
          </div>
          
          <!-- API详情 -->
          <ApiDetail v-else :current-api="currentApi" />
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, computed, onMounted, onBeforeUnmount } from 'vue';
import Sidebar from './components/Sidebar.vue';
import ApiDetail from './components/ApiDetail.vue';
import axios from 'axios';
import type { APIModule,SimpleApiInfo } from './api/model';


export default defineComponent({
  name: 'App',
  components: {
    Sidebar,
    ApiDetail
  },
  setup() {
    const apiData = ref<APIModule[]>([]);
    const sidebarHidden = ref(false);
    const loading = ref(true);
    const error = ref('');
    const currentApi = ref<SimpleApiInfo | null>(null);
    const expandedModules = ref<Record<string, boolean>>({});
    
    const totalCount = computed(() => {
      if (!apiData.value) return 0;
      let count = 0;
      apiData.value.forEach(module => {
        if (module.apis && Array.isArray(module.apis)) {
          count += module.apis.length;
        }
      });
      return count;
    });
    
    const enhanceApi = (api: any, category?: string): SimpleApiInfo => {
      api.module = category || '未分类';
      if (!api.name) api.name = '未命名接口';
      if (!api.method) api.method = 'GET';
      return api as SimpleApiInfo;
    };
    
    const loadApiData = async () => {
      loading.value = true;
      error.value = '';
      
      try {
        const response = await axios.get<APIModule[]>('/docs/api');
        const data:APIModule[] = response; // 正确提取axios响应数据
        if (data && Array.isArray(data)) {
          apiData.value = data;
          data.forEach((module: APIModule) => {
            const category = module.category || '未分类';
            if (Array.isArray(module.apis)) {
              module.apis.forEach((api: any) => enhanceApi(api, category));
            }
            expandedModules.value[category] = true;
          });
        } else {
          throw new Error('数据格式不正确，ret不为0或data不是数组');
        }
        
        loadApiFromUrl();
      } catch (err) {
        error.value = err instanceof Error ? err.message : '无法获取接口数据，请检查网络连接或稍后再试';
      } finally {
        loading.value = false;
      }
    };
    
    const toggleSidebar = () => {
      sidebarHidden.value = !sidebarHidden.value;
    };
    
    const toggleModule = (moduleName: string) => {
      expandedModules.value[moduleName] = !expandedModules.value[moduleName];
    };
    
    const showApiDetail = (api: SimpleApiInfo) => {
      currentApi.value = api;
      const url = new URL(window.location.href);
      // url.searchParams.set('module', module.category);
      // url.searchParams.set('api', api.name);
      url.searchParams.set('id', api.id);
      window.history.pushState({}, '', url);
    };
    
    const loadApiFromUrl = () => {
      const url = new URL(window.location.href);
      const id = url.searchParams.get('id');
      
      // 优先通过id查找API
      if (id) {
        for (const module of apiData.value || []) {
          const api = module.apis?.find((a: SimpleApiInfo) => a.id === id);
          if (api) {
            currentApi.value = api;
            return;
          }
        }
      }
      
      // 保留原有的通过module和api名称查找的逻辑
      const moduleName = url.searchParams.get('module');
      const apiName = url.searchParams.get('api');
      
      if (moduleName && apiName) {
        const module = apiData.value?.find(m => m.category === moduleName);
        if (module) {
          const api = module.apis.find((a: SimpleApiInfo) => a.name === apiName);
          if (api) {
            currentApi.value = api;
          }
        }
      }
    };
    
    const handleResize = () => {
      if (window.innerWidth > 768) {
        sidebarHidden.value = false;
      }
    };
    
    // showToast 函数已移除，根据需求不再需要该功能
    
    onMounted(() => {
      loadApiData();
      window.addEventListener('resize', handleResize);
    });
    
    onBeforeUnmount(() => {
      window.removeEventListener('resize', handleResize);
    });
    
    return {
      apiData,
      sidebarHidden,
      loading,
      error,
      currentApi,
      expandedModules,
      totalCount,
      toggleSidebar,
      toggleModule,
      showApiDetail
    };
  }
});
</script>

<style>
/* 全局样式和CSS变量定义 */
:root {
  /* 主题色彩变量 */
  --theme-color: #3498db;
  --theme-color-hover: #2980b9;
  --sidebar-bg: #f8f9fa;
  --content-bg: #ffffff;
  --heading-color: #2c3e50;
  --text-color: #333333;
  --text-muted: #666666;
  --border-color: #e1e4e8;
  --highlight-bg: #f0f7ff;
  --code-bg: #f6f8fa;
  --success-color: #28a745;
  --warning-color: #ffc107;
  --danger-color: #dc3545;
  --info-color: #17a2b8;
  
  /* 尺寸变量 */
  --sidebar-width: 280px;
  --header-height: 60px;
  --border-radius: 4px;
  --shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.05);
  --shadow-md: 0 4px 6px rgba(0, 0, 0, 0.1);
  
  /* 字体变量 */
  --font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
    sans-serif;
  --font-mono: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace;
}

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  font-family: var(--font-family);
  color: var(--text-color);
  background-color: var(--content-bg);
  line-height: 1.6;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}
  /* 标题样式 */
  .header-title {
    font-size: 18px;
    font-weight: 600;
    color: var(--heading-color);
    margin: 0;
    padding: 0;
  }
  
  .menu-toggle {
    background: var(--sidebar-bg);
    border: 1px solid var(--border-color);
    color: var(--text-color);
    padding: 6px 10px;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
    transition: all 0.3s;
}

.menu-toggle:hover {
    background: var(--highlight-bg);
    border-color: var(--theme-color);
}
  
  
  .menu-toggle:active {
    transform: scale(0.95);
  }
  
  /* 收缩状态样式 */
  .sidebar-collapsed .menu-toggle {
    transform: rotate(180deg);
  }
</style>

<style scoped>
  
  #app {
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: hidden;
}

.header {
  height: var(--header-height);
  background-color: var(--content-bg);
  border-bottom: 1px solid var(--border-color);
  display: flex;
  align-items: center;
  padding: 0 20px;
  position: relative;
  z-index: 10;
}

.menu-toggle {
  background: var(--sidebar-bg);
  border: 1px solid var(--border-color);
  color: var(--text-color);
  padding: 6px 10px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  margin-right: 15px;
  transition: all 0.3s;
}

.header h1 {
  font-size: 20px;
  font-weight: 500;
  color: var(--theme-color);
  margin: 0;
}

.main-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.content {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.api-content {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

/* 加载状态 */
.loading {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
  color: var(--text-muted);
}

/* 统计信息 */
.stats-info {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 30px;
}

.stat-item {
  background-color: var(--content-bg);
  border-radius: var(--border-radius);
  padding: 20px;
  min-width: 150px;
  text-align: center;
  box-shadow: var(--shadow-sm);
  border: 1px solid var(--border-color);
}

.stat-number {
  font-size: 32px;
  font-weight: bold;
  color: var(--theme-color);
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: var(--text-muted);
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: var(--text-muted);
}

.empty-state h3 {
  font-size: 20px;
  color: var(--heading-color);
  margin-bottom: 10px;
  font-weight: 500;
}

.empty-state p {
  font-size: 16px;
  margin-bottom: 20px;
}

/* 分享部分 */
.share-section {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}

.share-section label {
  font-size: 14px;
  color: var(--text-muted);
  white-space: nowrap;
}

.share-link {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius);
  font-size: 14px;
  background-color: var(--content-bg);
  font-family: var(--font-mono);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: var(--text-color);
}

/* 页脚 */
.footer {
  padding: 15px 20px;
  border-top: 1px solid var(--border-color);
  text-align: center;
  font-size: 14px;
  color: var(--text-muted);
  background-color: var(--content-bg);
}

/* 响应式设计 */
@media (max-width: 768px) {
  :root {
    --sidebar-width: 250px;
  }
  
  .menu-toggle {
    display: block;
  }
  
  .header h1 {
    font-size: 18px;
  }
  
  .api-content {
    padding: 15px;
  }
  
  .stats-info {
    gap: 15px;
  }
  
  .stat-item {
    padding: 15px;
    min-width: 120px;
  }
  
  .stat-number {
    font-size: 24px;
  }
}

@media (max-width: 480px) {
  .header {
    padding: 0 15px;
  }
  
  .api-content {
    padding: 10px;
  }
}

/* 滚动条美化 */
::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb {
  background: #ccc;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb:hover {
  background: #aaa;
}

/* Toast提示 */
.toast {
  animation: fadeInOut 3.3s ease-in-out;
}

@keyframes fadeInOut {
  0% { opacity: 0; }
  3% { opacity: 1; }
  97% { opacity: 1; }
  100% { opacity: 0; }
}
</style>